package com.tnsw.facebookautoliker.services;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.FacebookException;
import com.facebook.Session;
import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.StaticConfig;
import com.tnsw.coreutils.database.DBManagerBase;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.coreutils.files.FileUtils;
import com.tnsw.coreutils.queuemanager.QDelegateManager;
import com.tnsw.facebookautoliker.MainActivity;
import com.tnsw.facebookautoliker.helper.FacebookActionListener;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.helper.command.DoLikeObject;
import com.tnsw.facebookautoliker.helper.command.DoUnlikeObject;
import com.tnsw.facebookautoliker.helper.command.FQLBase;
import com.tnsw.facebookautoliker.helper.command.FQLInterface;
import com.tnsw.facebookautoliker.helper.command.GetHTTPPhoto;
import com.tnsw.facebookautoliker.helper.command.GetPhoto;
import com.tnsw.facebookautoliker.helper.command.LikeManager;
import com.tnsw.facebookautoliker.helper.command.SQLiteSelect;

import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.database.FriendsPost;
import com.tnsw.facebookautoliker.database.LikePostId;
import com.tnsw.facebookautoliker.database.ObjectCache;
import com.tnsw.facebookautoliker.database.SelfInfo;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Build;

public class AutoLikerService extends IntentService implements FacebookActionListener, FQLInterface {

	public static Class[] NETWORK_EXCEPTIONS = {java.net.ConnectException.class, java.io.EOFException.class};
	private String tag = "AutoLikerService";
	private static AutoLikerService sInstance;
	
	private DBManager dbm;
	private FacebookBGManager fbm;
	private GeneralManager gm;
	private LikeManager lm;
	
	private Timer timer;
	private AutoLikerTimerTask task;
	
	private SelfInfo selfInfo = null;
	private Hashtable<String, FriendsList> hashFriendsList;		// <id, FriendsList>
	private ArrayList<FriendsPost> arrWaitLike;		// Wait to be "Like"
	
	private float timerIntervalMinute = 0.5f;
	
	private Activity currentActivity;
	
	public AutoLikerService() {
		super("");
				
		//this.initialize();
		
		MyLog.d(tag, "Constructor('')");
	}
	
	public AutoLikerService(String name) {
		super(name);
		
		//this.initialize();
		MyLog.d(tag, "Constructor(name=" + name + ")");
	}
	
	public AutoLikerTimerTask getTimerTask() {
		return(this.task);
	}
	
	public Timer getTimer() {
		return(this.timer);
	}
	
	private void initialize() {
		
		if (MainActivity.IS_INITIALZED == false) {
			StaticConfig.ASYNC_THREAD_COUNT = 3;
			MyLog.enableNetworkLog = true;
			MyLog.isProduction = false;
			this.gm = GeneralManager.getInstance();
			
			if (Build.PRODUCT.startsWith("sdk") == false) {
				// Suppose to be real device, change Remote Log to remote server instead of VM
				StaticConfig.LOG_URL = "http://202.57.128.248/PredictWeb/NetworkLog.aspx";
			}
			
			DBManagerBase.DB_DIRECTORY = "com.tnsw.facebookautoliker";
			DBManagerBase.DB_FILE = "autoliker.s3db";
			DBManagerBase.REPLACED_FROM_ASSET_ALWAYS = false;
			DBManagerBase.REPLACED_FROM_ASSET_IF_ASSET_IS_NEWER = true;
		}
		
		this.gm = GeneralManager.getInstance();
		this.dbm = DBManager.getInstance(this);
		this.fbm = FacebookBGManager.getInstance(this);	
		this.fbm.registerActionListener(this);
		
		
		
		this.loadSelfInfo();
		
		this.hashFriendsList = new Hashtable<String, FriendsList>();
		this.loadFriendsList();
		
		this.arrWaitLike = new ArrayList<FriendsPost>();
		this.refreshWaitLike();
		
		this.lm = new LikeManager(this, this.selfInfo);
		
		ArrayList<Object> a = this.dbm.getRawRecords("select max(created_time) from friends_post", null, 0);
		if (a != null) {
			ArrayList<Object> aa = (ArrayList<Object>) a.get(0);
			if (aa.get(0) != null) {
				long l = (Long) aa.get(0);
				MyLog.d(tag, "l=" + l);	
			} else {
				MyLog.w(tag, "cannot find max(created_time), it's null, may be friends_post is empty");
			}
			
		}
		
		this.startTimer();
		
		sInstance = this;
	}
	
	public float getTimerIntervalMinute() {
		return(this.timerIntervalMinute);
	}
	
	public void tempStopTimer() {
		
		if (this.timer != null) {
			this.timer.cancel();
			this.timer.purge();
			this.timer = null;
			MyLog.d(tag, "tempStopTimer() is called");
		}
	}
	
	public void refreshWaitLike() {
		MyLog.d(tag, "refreshFriendsPost() -- starting..");
		try {
			if (this.arrWaitLike == null) {
				this.arrWaitLike = new ArrayList<FriendsPost>();
				
			} else {
				this.arrWaitLike.clear();
			}
			
			String sql = "select primarykey, post_id, liked from friends_post where liked in ('W', 'R') and created_time > " + this.getLast24hrSec() + " order by created_time desc";
			ArrayList<RecordBase> a = this.dbm.getRecords(FriendsPost.class.getName(), sql, null, 0);
			if (a != null) {
				int len = a.size();
				int i;
				for (i = 0; i < len; i++) {
					this.arrWaitLike.add((FriendsPost) a.get(i)); 
					MyLog.d(tag, "added to ArrWaitLike: " + a.get(i).toString());
				}
			}
			
			
		} catch (Exception e) {
			MyLog.e(tag, "refreshFriendsPost()- " + e.toString(), e);
		}
		MyLog.d(tag, "refreshFriendsPost() -- end");
	}
	
	public ArrayList<FriendsPost> getArrWaitLike() {
		return(this.arrWaitLike);
	}
	
	public void addNewWaitLike(FriendsPost fp) {
		int idx = this.findWaitLikeByPostId(this.arrWaitLike, fp.post_id);
		if (idx == -1) {
			this.arrWaitLike.add(fp);
			MyLog.d(tag, "added NewWaitLike: " + fp.post_id);
		}
	}
	
	public void removeWaitLike(int idx) {
		if (idx != -1) {
			MyLog.d(tag, "removeWaitLike(idx=" + idx + ")");
			this.arrWaitLike.remove(idx);
		}
	}
	
	public void removeWaitLike(String post_id) {
		int idx = this.findWaitLikeByPostId(this.arrWaitLike, post_id);
		if (idx != -1) {
			this.removeWaitLike(idx);
		} else {
			MyLog.w(tag, "Cannot removeWaitLike(post_id=" + post_id + ") -- not found in arrWaitLike");
		}
	}
	
	public int findWaitLikeByPostId(ArrayList<FriendsPost> afp, String post_id) {
		if (afp == null) { return(-1); }
		if (afp.size() == 0) { return(-1); }
		
		FriendsPost fp = null;
		int len = afp.size();
		int i;
		for (i = 0; i < len; i++) {
			if (afp.get(i).post_id.equals(post_id)) {
				return(i);
			}
		}
		
		return(-1);
	}
	
	public void _refreshFriendsListTemp() {
		this.hashFriendsList.clear();
		ArrayList<RecordBase> a = dbm.getRecords("com.tnsw.facebookautoliker.database.FriendsList", "select * from friends_list order by name", null, 0);
		if (a != null) {
			int len = a.size();
			int i;
			for (i = 0; i < len ; i++) {
				FriendsList fl = (FriendsList) a.get(i);
				this.hashFriendsList.put(fl.id, fl);
			}
		}
	}
	
	private void loadFriendsList() {
		// To load FriendsList into Hashtable
		ArrayList<RecordBase> a = dbm.getRecords(FriendsList.class.getName(), "select * from friends_list order by name", null, 0); 
		
		if (a == null) return;
		if (a.size() == 0) return;
		
		int len = a.size();
		int i;
		for (i = 0; i < len; i++) {
			FriendsList fl = (FriendsList) a.get(i);
			this.updateFriendsList(fl.id, fl);
			
		}
		
		MyLog.d(tag, "loadFriendsList() completed with " + len + " records");
		
		a = null;
		
	}
	
	public SelfInfo getSelfInfo() {
		return(this.selfInfo);
	}
	
	public Hashtable<String, FriendsList> getHashFriendsList() {
		return(this.hashFriendsList);
	}
	
	public void updateFriendsList(String id, FriendsList fl) {
		this.hashFriendsList.put(id, fl);
	}
	
	public void setSelfInfo(SelfInfo sInfo) {
		this.selfInfo = sInfo;
		this.lm.setSelfInfo(sInfo);
	}
	
	private void loadSelfInfo() {
		if (this.dbm != null) {
			ArrayList<RecordBase> a = this.dbm.getRecords(SelfInfo.class.getName(), "select * from self_info where primarykey=?", new String[] {"1"}, 0);
			if (a != null) {
				this.selfInfo = (SelfInfo) a.get(0);
			} else {
				MyLog.e(tag, "loadSelfInfo() - Cannot find self_info record with primarykey=1");
			}
		}
		
	}
	
	public void startTimer() {
		if (this.timer == null) {
			float minute = this.timerIntervalMinute;
			
			this.timer = new Timer(true);
			this.task = new AutoLikerTimerTask(this, this);
			this.timer.schedule(this.task, 0, (long) (minute*60*1000));
			
			//this.timer.cancel();
			
			MyLog.d(tag, "Timer is scheduled to run every " + minute + " minutes");
		}

	}
	
	public static AutoLikerService getInstance() {
		return(sInstance);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		MyLog.d(tag, "onHandleIntent(intent)");
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		MyLog.d(tag, "onStartCommand({intent}, flags=" + flags + ", startId=" + startId + ")");
		this.initialize();
		return(START_STICKY);
	}
	
	private void deleteLikePostId(String post_id, String xid) {
		boolean b = this.dbm.executeSQL("delete from like_post_id where post_id=? and xid=?", new String[] {post_id, xid}, true);
		if (b == false) {
			MyLog.e(tag, "Cannot delete like_post_id(post_id=" + post_id + ", xid=" + xid + ")");
		}
	}
	
	/**
	 * To update/insert table like_post_id
	 */
	private void updateLikePostId(FriendsPost fp, String xid) {
		MyLog.d(tag, "updateLikePostId(post_id=" + fp.post_id + ", xid=" + xid + ", created=" + fp.created_time + ")");
				
 		ArrayList<RecordBase> a = this.dbm.getRecords(LikePostId.class.getName(), "select * from like_post_id where post_id=? and xid=?", new String[] {fp.post_id, xid}, 0);
		if (a == null) {
			// not found
			LikePostId lp = new LikePostId();
			lp.primarykey = this.dbm.getNewPrimarykey();
			lp.post_id = fp.post_id;
			lp.xid = xid;
			lp.post_id_created = fp.created_time;
			lp.fp = fp.primarykey;
			
			this.dbm.insertRecord("like_post_id", lp, null, false);
			MyLog.d(tag, "> inserted..");
		}  else {
			MyLog.d(tag, "> record exists");
		}
		
	}
	
	@Override
	public void onRequestCompleted(Object sender, FacebookCommandObject fbco, int statusCode, Exception tr) {
		if ( (fbco instanceof GetHTTPPhoto) && (fbco.getTag("owner") != null) && (fbco.getTag("owner").equals(this)) ) {
			GetHTTPPhoto gp = (GetHTTPPhoto) fbco;
			ObjectCache oc = (ObjectCache) gp.getTag("record");
			if (oc != null) {
				oc.local_path = gp.getPhotoPath();
				MyLog.d(tag, "updating record to: " + oc.toString());
				this.dbm.updateRecordByPrimarykey("object_cache", oc, true);
			}
		}
		
		if (fbco instanceof GetPhoto) {
			GetPhoto gp = (GetPhoto) fbco;
			FriendsList fl = this.hashFriendsList.get(gp.getId());
			fl.photo_path = gp.getPhotoFileName();
		}
		
		if ( (fbco instanceof DoLikeObject) ) {
			MyLog.d(tag, "doLikeObject, isUIThread=" + GeneralManager.isUiThread());
			//DoLikeObject like = (DoLikeObject) fbco;
			FriendsPost fp = (FriendsPost) fbco.getTag("record");
			String xid = "";
			if (fbco.getTag("xid") != null) {
				xid = (String) fbco.getTag("xid");
			}
			if (fp != null) {
				// reselect again coz fp may come from AutoLikerService.arrWaitLike which is short record
				ArrayList<RecordBase> a = this.dbm.getRecords(FriendsPost.class.getName(), "select * from friends_post where post_id=?", new String[] {fp.post_id}, 0);
				if (a != null) {
					fp = (FriendsPost) a.get(0);
					
					if (statusCode == 200) {
						fp.liked = "Y";
						AutoLikerService aService = AutoLikerService.getInstance();
						FriendsList fl = aService.getFriend(fp.actor_id);
						if (fl != null) {
							fl.like_count += 1;
							if (fp.created_time < fl.like_count_since) {
								fl.like_count_since = fp.created_time;
							}
							
							aService.updateFriendsList(fl.id, fl);
							this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
							
						} else {
							MyLog.e(tag, "Cannot update FriendsList coz actor_id=" + fp.actor_id + " is not found");
						}
						
						
					} else {
						if (tr instanceof FacebookException) {
							fp.liked = "C";		// For sure cannot like coz Facebook exception	
						} else {
							fp.liked = "W";		// Can be liked later, suspected network problem
						}
						
					}
						
					int recordAffected = this.dbm.updateRecordByPrimarykey("friends_post", fp, true);
					if (recordAffected > 0) {
						MyLog.d(tag, "updated fp where post_id=" + fp.post_id + ", xid=" + xid);
					}
					
					this.updateLikePostId(fp, xid);
					
				}
				
				this.removeWaitLike(fp.post_id);
			}
					
		}
		
		if (fbco instanceof SQLiteSelect) {
			SQLiteSelect s = (SQLiteSelect) fbco;
			if (s.hasTag("name")) {
				String name = (String) s.getTag("name");
				if (name.equals("doSummary")) {
					String actor_id = (String) s.getTag("actor_id");
					if (s.hasTag("result")) {
						
						@SuppressWarnings("unchecked")
						ArrayList<Object> a = (ArrayList<Object>) s.getTag("result");
						MyLog.d(tag, "count_test, length=" + a.size());
						
						@SuppressWarnings("unchecked")
						ArrayList<Object> aa = (ArrayList<Object>) a.get(0);
						long count = (Long) aa.get(0);
						long minCreated = (Long) aa.get(1);
						MyLog.d(tag, "count_test, record_count=" + count + ", min=" + minCreated);
						
						FriendsList fl = this.hashFriendsList.get(actor_id);
						if (fl != null) {
							fl.like_count = (int) count;
							fl.like_count_since = minCreated;
							this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
							MyLog.d(tag, "updated friends_list for like counting");	
						} else {
							MyLog.e(tag, "Cannot find actor_id=" + actor_id + " from hashFriendsList");
						}
						
						
						
					}
				}
			}
		}
	}

	@Override
	public boolean onSingleRecordFetched(Object sender, int recordNo, JSONObject jo) {
		FQLBase f = (FQLBase) sender;
		this.processRecord(f, jo);
		
		return(false);
		
	}
	

	private void updateLikeCount(JSONObject jo, FriendsPost fp) throws JSONException {
		// Upload like count, can/cannot like for this stream
		
		boolean canLike = false;
		String current_liked = fp.liked;
		
		if (jo.has("like_info")) {
			JSONObject jLikes = (JSONObject) jo.get("like_info");
			if (jLikes.has("can_like")) {
				canLike = jLikes.getBoolean("can_like");
				if (canLike == true) {
					fp.can_like = "Y";
				} else {
					fp.can_like = "N";
					fp.liked = "N";
				}
			}
			
			if (jLikes.getBoolean("user_likes") == true) {
				// User already likes this before using AutoLiker
				fp.liked = "Y";
			} else {
				fp.liked = "N";
			}
			
			if (jLikes.has("like_count")) {
				int like_count = jLikes.getInt("like_count");
				fp.like_count = like_count;
			}
			
			if ( (current_liked.equals(fp.liked) == false) && (current_liked.equals("") == false) ) {
				// like status is not the same, the stat may be changed, should re-query and update again
				this.refreshLikeForFriends(fp.actor_id);
				
			}
		}		
	}
	
	private void refreshLikeForFriends(String actor_id) {
		MyLog.d(tag, "calling refreshLikeForFriends(actor_id=" + actor_id + ")");
		String sql = "select count(*), min(created_time) from v_like_post_id where actor_id=?";
		
		ArrayList<Object> a = this.dbm.getRawRecords(sql, new String[] { actor_id }, 0);
		if (a != null) {
			ArrayList<Object> aa = (ArrayList<Object>) a.get(0);
			long count = (Long) aa.get(0);
			long min_created = 0;
			if (aa.get(1) != null) {
				min_created = (Long) aa.get(1);	
			}
						
			ArrayList<RecordBase> flA = this.dbm.getRecords(FriendsList.class.getName(), "select * from friends_list where id=?", new String[] {actor_id}, 0);
			if (flA != null) {
				FriendsList fl = (FriendsList) flA.get(0);
				fl.like_count = (int) count;
				fl.like_count_since = min_created;
			
				this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
			}
						
		}
		
	}
	
	public void processRecord(FQLBase f, JSONObject jo) {
		MyLog.d(tag, "processing record..");
		
		String source_id = (String) f.getTag("source_id");
		if (source_id.equals("me()")) {
			if (this.selfInfo != null) {
				source_id = this.selfInfo.id;
			}
		} 

		FriendsPost fp = new FriendsPost();
		
		try {
			if (jo.has("post_id")) {
				fp.post_id = jo.getString("post_id");
				MyLog.d(tag, "post_id=" + fp.post_id);
			}
			
			ArrayList<RecordBase> a = this.dbm.getRecords(FriendsPost.class.getName(), "select * from friends_post where post_id=?", new String[] {fp.post_id}, 0);
			if (a == null) {  // This is new timeline for me
				fp.source_id = source_id;
				MyLog.d(tag, "Using source_id=" + fp.source_id);
				fp.primarykey = this.dbm.getNewPrimarykey();
				
				//fp.raw_json = rawJson;
				fp.liked = "W";
				fp.status_type = "X";
				
				if (jo.has("created_time")) {
					fp.created_time = jo.getLong("created_time");
				}
				
				if (jo.has("updated_time")) {
					fp.updated_time = jo.getLong("updated_time");
				}

				if (jo.has("actor_id")) {
					fp.actor_id = jo.getString("actor_id");
				}
				
				this.updateLikeCount(jo, fp);
				
				String name = "";
				String status_text = "";
				if (this.hashFriendsList.containsKey(fp.actor_id) == true) {
					name = this.hashFriendsList.get(fp.actor_id).name;
				}
				
				if (jo.has("type") == true) {
					
					status_text = LikeManager.getType(jo, name);
					fp.status_text = status_text;
					fp.type = jo.getInt("type");
				}
				
				if (jo.has("description")) {
					String description = jo.getString("description");
					if (description.length() > 1000) {
						description = description.substring(0, 999);
					}
					
					fp.description = description;
				}
				
				if (jo.has("message")) {
					String message = jo.getString("message");
					if (message.length() > 1000) {
						message = message.substring(0, 999);
					}
					
					fp.message = message;
				}				
				
				long rowId = this.dbm.insertRecord("friends_post", fp, null, true);
				if (rowId != -1l) {
					if (fp.liked.equals("N")) {
						this.addNewWaitLike(fp);	
					} else {
						// You have already like this from another facebook app
						rowId = this.addLikePostId(fp);
						if (rowId != -1l) {
							this.refreshLikeForFriends(fp.actor_id);
						}
					}
										
				}
				
			} else {
				MyLog.d(tag, "record exists!");
				fp = (FriendsPost) a.get(0);
				this.updateLikeCount(jo, fp);
				
				this.dbm.updateRecordByPrimarykey("friends_post", fp, true);
				
			}
							
			this.handleAttachment(jo, fp.status_text);
			
		} catch (JSONException je) {
			MyLog.e(tag, "processRecord (JSONException) - " + jo.toString(), je);
			
		} catch (Exception e) {
			MyLog.e(tag, "processRecord - " + e.toString(), e);
		}		
	}
	
	private Long addLikePostId(FriendsPost fp) {
		long l = -1;
		ArrayList<RecordBase> a = this.dbm.getRecords(LikePostId.class.getName(), "select * from like_post_id where post_id=? and xid=?", new String[] {fp.post_id, fp.post_id}, 0);
		if (a == null) {
			LikePostId lpi = new LikePostId();
			lpi.primarykey = this.dbm.getNewPrimarykey();
			lpi.fp = fp.primarykey;
			lpi.post_id = fp.post_id;
			lpi.post_id_created = fp.created_time;
			lpi.xid = fp.post_id;
			
			l = this.dbm.insertRecord("like_post_id", lpi, null, false);
		}
		
		return(l);
	}
	
	public void handleAttachment(JSONObject jo, String typeStt) {
		try {
			boolean b = false;

			if (jo.has("attachment")) {
				JSONObject jAttachment = jo.getJSONObject("attachment");
				if (jAttachment.has("media")) {
					JSONArray jMediaArray = jAttachment.getJSONArray("media");
					int len = jMediaArray.length();
					int i;
					for (i = 0; i < len; i++) {
						ObjectCache oc = new ObjectCache();
						
						if (jo.has("post_id")) {
							oc.post_id = jo.getString("post_id");
						}
						
						if (jo.has("actor_id")) {
							oc.owner = jo.getString("actor_id");
						}
						
						if (jo.has("created_time")) {
							oc.created_time = jo.getLong("created_time");
						}	
												
						JSONObject jMedia = (JSONObject) jMediaArray.get(i);
						
						if (jMedia.has("type")) {
							oc.type = jMedia.getString("type");
						}
						
						if (oc.type.equals("photo")) {
							if (jMedia.has("src")) {

								oc.src = jMedia.getString("src");
								MyLog.d(tag, "src=" + oc.src);
																
								JSONObject jPhoto = jMedia.getJSONObject("photo");
								oc.fbid = jPhoto.getString("fbid");
								b = true;
								 
							}
							
						} else if (oc.type.equals("link")) {
							oc.src = jMedia.getString("src");
							oc.fbid = jo.getString("post_id");
							b = true;
							
						} else if (oc.type.equals("video")) {
							JSONObject jVideo = jMedia.getJSONObject("video");
							oc.src = jMedia.getString("src");
							String source_url = jVideo.getString("source_url");
							oc.source_url = source_url;
							oc.fbid = oc.post_id;
							b = true;
						}
						
						
						if (b) { // sufficient information for inserting to database
							ArrayList<RecordBase> a = this.dbm.getRecords(ObjectCache.class.getName(), "select * from object_cache where fbid=?", new String[] {oc.fbid}, 0);
							if (a == null) {
								
								oc.primarykey = this.dbm.getNewPrimarykey();
								MyLog.d(tag, "Not found fbid=" + oc.fbid + ", " + oc.toString());
								
								long result = this.dbm.insertRecord("object_cache", oc, "local_path", true);
								MyLog.d(tag, "insert object_cache result=" + result);
							} else {
								oc = (ObjectCache) a.get(0);
								MyLog.d(tag, "Found existing obejct_cache, " + oc.toString());
							}
							
							if (oc.local_path == null) {
								MyLog.d(tag, "Found empty local_path, fbid=" + oc.fbid);
								GetHTTPPhoto gp = new GetHTTPPhoto(this, oc.src, oc.fbid);
								gp.setTag("record", oc);
								gp.setTag("owner", this);
								this.gm.addNewQueue(gp, 2);
							}
																					
						} else {
							MyLog.w(tag, "Not enough information to work with object_cache record");
						}
						
						b = false;
					}
				} else if (typeStt.equals(LikeManager.S_LIKED_SOMETHING)) {
					// Liked something which does not have media in attachment
					MyLog.d(tag, "Cannot find attachment from " + LikeManager.S_LIKED_SOMETHING);
					String post_id = jo.getString("post_id");
					String xid = post_id.split("_")[1];
					MyLog.d(tag, "xid=" + xid);
				}
				
			} 
			

			
		} catch (Exception e) {
			MyLog.e(tag, "testGETHttpPhoto - " + e.toString(), e);
		}		
	}
	
	private long getLast24hrSec() {
		long sec = 0;
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		c.add(Calendar.HOUR, -24);
		sec = c.getTimeInMillis() / 1000;
		
		return(sec);
	}
	
	public FriendsList getFriend(String actorId) {
		if (this.hashFriendsList.containsKey(actorId) == true) {
			return(this.hashFriendsList.get(actorId));
		}
		
		return(null);
	}
	
	public FriendsList getFriendFromDB(String actorId) {
		ArrayList<RecordBase> a = this.dbm.getRecords(FriendsList.class.getName(), "select * from friends_list where id=?", new String[] {actorId}, 0);
		if (a != null) {
			FriendsList fl = (FriendsList) a.get(0);
			return(fl);
		} else {
			return null;
		}
	}

	@Override
	public void onEndQuery(Object sender, ArrayList<JSONObject> arrJ) {
		
	}

	public void setCurrentActivity(Activity a) {
		this.currentActivity = a;
	}
	
	public Activity getCurrentActivity() {
		return(this.currentActivity);
	}
}
